import React, { useEffect } from 'react';
import { connect, useDispatch } from 'react-redux';
import { Navigate } from 'react-router-dom';
import * as  apiList from '@/apis/login';
import { SAVE_PERMISSIONS } from '@/reducers/common';


function PrivateComponent(props: any) {
    const dispatch = useDispatch()
    useEffect(() => {
        const { loginInfo, permissions } = props;
        if (!loginInfo) return;
        if (!permissions || !permissions.length) {
            getPermissions()
        }
    }, [props.permissions])
    async function getPermissions() {
        let res = await apiList.getPermissions()
        dispatch({ type: SAVE_PERMISSIONS, data: res.data.list })
    }
    return (
        props.loginInfo ? props.children : <Navigate to="/login" />
    )

}

export default connect((state: any) => {
    let { loginInfo, permissions } = state.common;
    let l = localStorage['persist:__info__'] || null
    l = JSON.parse(l).loginInfo
    l = JSON.parse(l)
    if (l && l.accountName && loginInfo && loginInfo.accountName && loginInfo.accountName != l.accountName) {
        permissions = []
    }
    return {
        loginInfo,
        permissions
    }
})(PrivateComponent)